package org.csu.mypetstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.csu.mypetstore.common.CommonResponse;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.OrderStatus;
import org.csu.mypetstore.mapper.CartMapper;
import org.csu.mypetstore.mapper.OrderStatusMapper;
import org.csu.mypetstore.service.OrderStatusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

@Service
public class OrderStatusServiceImpl implements OrderStatusService {

    @Autowired
    private OrderStatusMapper orderStatusMapper;

    @Autowired
    private CartMapper cartMapper;


    @Override
    public CommonResponse<List<OrderStatus>> getOrders() {
        return null;
    }

    @Override
    public boolean createOrder(OrderStatus orderStatus) {

        int result = orderStatusMapper.insert(orderStatus);
        if(result == 0){
            return false;
        }
        return true;
    }

    public CommonResponse<Object> payment(String user){
        int result = 1;
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user", user);
        List<Cart> cartList =  cartMapper.selectList(queryWrapper);
        result = cartMapper.delete(queryWrapper);
        if(result == 0){
            return CommonResponse.createForError("支付成功，但购物车未清空");
        }
        return CommonResponse.createForSuccessMessage("支付成功，购物车已清空");
    }

    @Override
    public String getSubject() {
        return getString(6);
    }

    @Override
    public String getTraceNo() {
        QueryWrapper<OrderStatus> queryWrapper = new QueryWrapper<>();
        OrderStatus orderStatus;
        String traceNo = "";
        do {
            traceNo = getString(9);
            queryWrapper.eq("orderid", traceNo);
            orderStatus = orderStatusMapper.selectOne(queryWrapper);
        }while(orderStatus != null);
        return traceNo;
    }

    @Override
    public String getString(int len) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < len; i++) {
            int digit = random.nextInt(10);
            sb.append(digit);
        }
        return sb.toString();
    }

}
